{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CSV 文件已成功保存\n"
     ]
    }
   ],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "\n",
    "#第一题\n",
    "import requests\n",
    "import json\n",
    "import csv\n",
    "cookies = {\n",
    "    'AlteonP10': 'A6pAFSw/F6ye2Yl2LfvlFA$$',\n",
    "    'apache': 'bbfde8c184f3e1c6074ffab28a313c87',\n",
    "    'ags': 'a23ede7e97bccb1b2380be21609ada80',\n",
    "    '_ulta_id.ECM-Prod.ccc4': '08fe72e24da7a44b',\n",
    "    '_ulta_ses.ECM-Prod.ccc4': 'c02ba244a49b5a54',\n",
    "}\n",
    "\n",
    "headers = {\n",
    "    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0',\n",
    "    'Accept': 'application/json, text/javascript, */*; q=0.01',\n",
    "    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n",
    "    # 'Accept-Encoding': 'gzip, deflate, br, zstd',\n",
    "    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n",
    "    'X-Requested-With': 'XMLHttpRequest',\n",
    "    'Origin': 'https://iftp.chinamoney.com.cn',\n",
    "    'Connection': 'keep-alive',\n",
    "    'Referer': 'https://iftp.chinamoney.com.cn/english/bdInfo/',\n",
    "    # 'Cookie': 'AlteonP10=A6pAFSw/F6ye2Yl2LfvlFA$$; apache=bbfde8c184f3e1c6074ffab28a313c87; ags=a23ede7e97bccb1b2380be21609ada80; _ulta_id.ECM-Prod.ccc4=08fe72e24da7a44b; _ulta_ses.ECM-Prod.ccc4=c02ba244a49b5a54',\n",
    "    'Sec-Fetch-Dest': 'empty',\n",
    "    'Sec-Fetch-Mode': 'cors',\n",
    "    'Sec-Fetch-Site': 'same-origin',\n",
    "    'Priority': 'u=0',\n",
    "}\n",
    "\n",
    "data = {\n",
    "    'pageNo': '1',\n",
    "    'pageSize': '30',\n",
    "    'isin': '',\n",
    "    'bondCode': '',\n",
    "    'issueEnty': '',\n",
    "    'bondType': '100001',\n",
    "    'couponType': '',\n",
    "    'issueYear': '2023',\n",
    "    'rtngShrt': '',\n",
    "    'bondSpclPrjctVrty': '',\n",
    "}\n",
    "\n",
    "response = requests.post(\n",
    "    'https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN',\n",
    "    cookies=cookies,\n",
    "    headers=headers,\n",
    "    data=data,\n",
    ")\n",
    "in_data = [['ISIN','Bond Code','Issuer','Bond Type','Issue Date','Latest Rating']]\n",
    "for page in range(1,int((int(json.loads(response.text)['data']['total'])/15))+2):\n",
    "    data = {\n",
    "        'pageNo': str(page),\n",
    "        'pageSize': '15',\n",
    "        'isin': '',\n",
    "        'bondCode': '',\n",
    "        'issueEnty': '',\n",
    "        'bondType': '100001',\n",
    "        'couponType': '',\n",
    "        'issueYear': '2023',\n",
    "        'rtngShrt': '',\n",
    "        'bondSpclPrjctVrty': '',\n",
    "    }\n",
    "\n",
    "    response = requests.post(\n",
    "        'https://iftp.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN',\n",
    "        cookies=cookies,\n",
    "        headers=headers,\n",
    "        data=data,\n",
    "    )\n",
    "    for i in json.loads(response.text)['data']['resultList']:\n",
    "        in_data.append([i['isin'],i['bondCode'],i['entyFullName'],i['bondType'],i['issueStartDate'],i['debtRtng']])\n",
    "# 保存到 CSV 文件\n",
    "with open('output.csv', mode='w', newline='', encoding='utf-8') as file:\n",
    "    writer = csv.writer(file)\n",
    "    writer.writerows(in_data)\n",
    "\n",
    "print(\"CSV 文件已成功保存\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'标的证券': ['600900.SH'], '换股期限': ['2027-6-1']}]\n"
     ]
    }
   ],
   "source": [
    "#第二题\n",
    "\n",
    "import re\n",
    "def reg_search(text,regex_list):\n",
    "    ret_res = []\n",
    "    json_res = {}\n",
    "    for item in regex_list:\n",
    "        for key in item.keys():\n",
    "            res = re.findall(item[key],text)\n",
    "            json_res[key] = res\n",
    "            for index,res_item in enumerate(res):\n",
    "                if '年' in res_item and '月' in res_item and '日' in res_item:\n",
    "                    data_res = re.findall('(\\d+)[\\s\\n]?年[\\s\\n]?(\\d+)[\\s\\n]?月[\\s\\n]?(\\d+)[\\s\\n]?日',res_item)\n",
    "                    res[index] = '{}-{}-{}'.format(data_res[0][0],data_res[0][1].zfill(2),data_res[0][2].zfill(2))\n",
    "            json_res[key] = res\n",
    "        ret_res.append(json_res)\n",
    "    return ret_res\n",
    "text = '''标的证券：本期发行的证券为可交换为发行人所持中国长江电力股份有限公司股票（股票代码：600900.SH，股票简称：长江电力）的可交换公司债券。换股期限：本期可交换公司债券换股期限自可交换公司债券发行结束之日满 12 个月后的第一个交易日起至可交换债券到期日止，即 2023 年 6 月 2 日至 2027 年 6 月 1 日止。'''\n",
    "regex_list=[{\n",
    "\t'标的证券': '[0-9]{5}\\.[A-Z]{2}',\n",
    "\t'换股期限': '\\d+[\\s\\n]?年[\\s\\n]?\\d+[\\s\\n]?月[\\s\\n]?\\d+[\\s\\n]?日'\n",
    "}]\n",
    "\n",
    "res = reg_search(text,regex_list)\n",
    "print(res)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
